package com.kajespero.json.process;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kajespero.json.annotation.JSonKind;
import com.kajespero.json.annotation.JSonMapping;
import com.kajespero.json.helper.ClassHelper;
import com.kajespero.json.helper.NumberUtils;


public class JSonMappingProcess {
	
	private static final Log LOG = LogFactory.getLog(JSonMappingProcess.class);

	
	public static <E, T> T getJsonClassTarget(Class<E> dto){
		return null;
	}
	
	public static <E> JSonKind getKind(Class<E> dto){
		JSonKind kindAnnotation = ClassHelper.getDeclaredAnnotation(dto, JSonKind.class);
		return kindAnnotation;
	}
	
	public static <E> Field getMappingField(String key, E instance){
		List<Field> fields = (List<Field>) ClassHelper.getField(instance.getClass(), JSonMapping.class);
		for (Field field : fields){
			JSonMapping annotation = field.getAnnotation(JSonMapping.class);
			String mappedBy = annotation.mappedBy().isEmpty() ? field.getName() : annotation.mappedBy();
			if(mappedBy.equals(key)){
				return field;
			}
		}
		return null;
	}
	
	public static <E> void setInstance(E instance, String key,  Object value){
		Field field  = getMappingField(key, instance);
		if(field != null){
			field.setAccessible(true);
			try {
				Class<?> classField = field.getType();
				Class<?> classValue = value.getClass();
				if(classField.getName().equals(classValue.getName())){
					field.set(instance, value);
				}
				else {
					field.set(instance, NumberUtils.convert(value, classField));
				}
				
				
			} catch (IllegalArgumentException e) {
				LOG.error("IllegalArgumentException " + e.getMessage(), e);
			} catch (IllegalAccessException e) {
				LOG.error("IllegalAccessException " + e.getMessage(), e);
			}
			finally{
				field.setAccessible(false);
			}
		}
		
	}
}
